import React, { useEffect, useState } from 'react';
import 'ray';
import '@/i18n';
import { initPanelEnvironment, initDevInfo, onDpDataChange, offDpDataChange } from '@ray-js/ray';
import { hooks } from '@ray-js/panel-sdk';
import { Provider } from 'react-redux';
import store from './redux';
import { devInfoChange } from './redux/modules/devInfoSlice';
import { formatDevSchema, formatDps } from './utils';
import { responseUpdateDp } from './redux/modules/dpStateSlice';

import '@/icon/iconfont.css';
import '@/global.less';

initPanelEnvironment({ useDefaultOffline: true });

const App = ({ children }) => {
  const [initialized, setInitialized] = useState(false);
  hooks.usePanelConfig();

  const handleDpDataChange: DpDataChangeHandler = data => {
    store.dispatch(responseUpdateDp(formatDps(data)));
  };

  useEffect(() => {
    const initializeState = async () => {
      const devInfoInitial = await initDevInfo();
      if (devInfoInitial) {
        store.dispatch(devInfoChange(formatDevSchema(devInfoInitial)));
        setInitialized(true);
      }
    };

    initializeState();
  }, []);

  useEffect(() => {
    onDpDataChange(handleDpDataChange);

    return () => {
      offDpDataChange(handleDpDataChange);
    };
  }, []);

  return <Provider store={store}>{initialized ? children : null}</Provider>;
};

export default App;
